from fastapi import APIRouter, HTTPException, Depends
from app.db.es_db import ElasticsearchClient
from sqlalchemy.orm import Session
from app.core.config import settings
from app.schemas.comment import CommentCreate, CommentResponse
from typing import List
from datetime import datetime


router = APIRouter()

@router.post("/", response_model=CommentResponse)
async def create_comment(comment: CommentCreate, db: ElasticsearchClient = Depends(ElasticsearchClient)):
    try:
        # 创建索引和映射
        mappings = {
            "properties": {
                "content": {"type": "text"},
                "user": {
                    "properties": {
                        "id": {"type": "keyword"},
                        "email": {"type": "keyword"},
                        "name": {"type": "keyword"},
                        "avatar": {"type": "keyword"}
                    }
                },
                "likes": {"type": "integer"},
                "replies": {"type": "nested"},
                "createdAt": {"type": "date"}
            }
        }
        db.create_index("comment", mappings=mappings)
        
        # Create the comment document first
        comment_doc = {
            "content": comment.content,
            "user": {
                "id": comment.user_id,
                "email": comment.user_email,
                "name": comment.user_name,
                "avatar": "https://joeschmoe.io/api/v1/random"
            },
            "likes": 0,
            "replies": [],
            "createdAt": datetime.now().isoformat()
        }
        
        # Then insert it into ES
        result = db.insert_document("comment", comment_doc)
        comment_doc["id"] = result["_id"]
        
        return comment_doc
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/", response_model=List[CommentResponse])
async def get_comments(user_id: str = None, db: ElasticsearchClient = Depends(ElasticsearchClient)):
    try:
        query = {
            "query": {
                "bool": {
                    "must": [{"match_all": {}}]
                }
            }
        }
        
        if user_id:
            query["query"]["bool"]["must"] = [{"match": {"user.id": user_id}}]
        
        # 添加调试日志
        print("查询参数:", query)
        results = db.search("comment", query)
        print("ES返回结果:", results)
        
        if not isinstance(results, list):
            print("返回格式不是列表，尝试直接使用返回数据")
            return []
            
        comments = []
        for item in results:
            source = item.get("_source", {})
            comment = {
                "id": item.get("_id"),
                "content": source.get("content"),
                "user": {
                    "name": source.get("user", {}).get("name"),
                    "avatar": source.get("user", {}).get("avatar")
                },
                "likes": source.get("likes", 0),
                "replies": source.get("replies", []),
                "createdAt": source.get("createdAt")
            }
            comments.append(comment)
        
        # 添加调试日志
        print("处理后的评论数据:", comments)
        return comments
    except Exception as e:
        print(f"获取评论失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/{comment_id}/reply", response_model=CommentResponse)
async def create_reply(
    comment_id: str,
    reply: CommentCreate,
    db: ElasticsearchClient = Depends(ElasticsearchClient)
):
    try:
        # 获取原评论
        result = db.get_document("comment", comment_id)
        if not result:
            raise HTTPException(status_code=404, detail="评论不存在")
        
        comment = result.get("_source", {})
        
        # 创建新回复，添加 id 字段
        new_reply = {
            "id": f"{comment_id}_reply_{len(comment.get('replies', []))}",
            "content": reply.content,
            "user": {
                "id": reply.user_id,
                "email": reply.user_email,
                "name": reply.user_name,
                "avatar": "https://joeschmoe.io/api/v1/random"
            },
            "likes": 0,
            "replies": [],
            "createdAt": datetime.now().isoformat()
        }
        
        # 更新评论的回复列表
        replies = comment.get("replies", [])
        replies.append(new_reply)
        
        # 使用 es 的原生更新方法
        update_result = db.es.update(
            index="comment",
            id=comment_id,
            body={
                "doc": {
                    "replies": replies
                }
            }
        )
        if not update_result:
            raise HTTPException(status_code=500, detail="更新评论失败")
            
        return new_reply
    except Exception as e:
        print(f"回复评论失败: {e}")
        raise HTTPException(status_code=500, detail=f"回复评论失败: {str(e)}")


@router.post("/{comment_id}/like", response_model=CommentResponse)
async def like_comment(
    comment_id: str,
    db: ElasticsearchClient = Depends(ElasticsearchClient)
):
    try:
        # Get original comment
        result = db.get_document("comment", comment_id)  # 修改这里
        if not result:
            raise HTTPException(status_code=404, detail="评论不存在")
        
        comment = result.get("_source", {})
        current_likes = comment.get("likes", 0)
        
        # Update like count
        update_result = db.es.update(
            index="comment",  # 修改这里
            id=comment_id,
            body={
                "doc": {
                    "likes": current_likes + 1
                }
            },
            refresh=True
        )
        
        # Return complete comment object with all required fields
        updated_comment = {
            "id": comment_id,
            "content": comment.get("content", ""),
            "user": comment.get("user", {
                "name": "当前用户",
                "avatar": "https://joeschmoe.io/api/v1/random"
            }),
            "likes": current_likes + 1,
            "replies": comment.get("replies", []),
            "createdAt": comment.get("createdAt", datetime.now().isoformat())
        }
        
        return updated_comment
        
    except Exception as e:
        print(f"点赞失败: {e}")
        raise HTTPException(status_code=500, detail=f"点赞失败: {str(e)}")

